<template>
  <div class="container" ref="content" @click="restTip">
    <div class="card">
      <div class="time-action">
        <div class="item-container">
          <div
            class="item"
            :class="{ active: currentType === 0 }"
            @click="onChangeType(0)"
          >
            {{ $t("energy.day") }}
          </div>
          <div
            class="item"
            :class="{ active: currentType === 2 }"
            @click="onChangeType(2)"
          >
            {{ $t("energy.weekly") }}
          </div>
          <div
            class="item"
            :class="{ active: currentType === 3 }"
            @click="onChangeType(3)"
          >
            {{ $t("energy.month") }}
          </div>
          <div
            class="item"
            :class="{ active: currentType === 4 }"
            @click="onChangeType(4)"
          >
            {{ $t("energy.year") }}
          </div>
        </div>
      </div>
      <div
        class="content"
        :class="{
          'content-right': currentType === 0,
          'content-left': currentType === 4,
        }"
      >
        <div class="actions">
          <div
            class="action-item"
            :class="{ active: isShowSolar }"
            @click="restSelect('isShowSolar')"
          >
            <img
              v-if="isShowSolar"
              src="@/assets/images/system/ic_solar_light.png"
              alt=""
            />
            <img v-else src="@/assets/images/system/ic_solar.png" alt="" />
          </div>
          <div
            :class="{
              batteryItem: isShowBattery || isShowGrid,
              active: isShowBattery,
            }"
            class="action-item"
            @click="restSelect('isShowBattery')"
          >
            <img
              v-if="isShowBattery"
              :src="'energy/ic_battery_light.png' | formatterPic"
              alt=""
            />
            <img v-else :src="'system/ic_battery.png' | formatterPic" alt="" />
          </div>
          <div
            :class="{
              batteryItem: isShowBattery || isShowGrid,
              active: isShowHome,
            }"
            class="action-item"
            @click="restSelect('isShowHome')"
          >
            <img
              v-if="isShowHome"
              :src="'energy/ic_home_light.png' | formatterPic"
              alt=""
            />
            <img v-else src="@/assets/images/system/ic_home.png" alt="" />
          </div>
          <div
            v-if="isShowGridItem"
            :class="{
              batteryItem: isShowBattery || isShowGrid,
              active: isShowGrid,
            }"
            class="action-item"
            @click="restSelect('isShowGrid')"
          >
            <img
              v-if="isShowGrid"
              :src="'energy/compass_light.png' | formatterPic"
              alt=""
            />
            <img v-else :src="'energy/compass.png' | formatterPic" alt="" />
          </div>
        </div>
        <div class="headers">
          <div class="solar-container" v-if="!isShowBattery && !isShowGrid">
            <div class="power">
              {{
                isShowSolar
                  ? handler().formatterNum(solarTotal)
                  : isShowHome
                  ? handler().formatterNum(homeTotal)
                  : 0
              }}
            </div>
            <div class="text">
              {{
                isShowSolar
                  ? $t("system.fromSolar")
                  : isShowHome
                  ? $t("energy.homeusage")
                  : 0
              }}
            </div>
            <div class="icon" @click.stop="isShowSolarTip = !isShowSolarTip">
              <img :src="'energy/ic_tip.png' | formatterPic" alt="" />
              <div v-if="isShowSolarTip" class="bubble-tail" />
            </div>
            <div class="bubble" v-if="isShowSolarTip">
              <div class="bubble-content">
                {{ isShowSolar ? $t("system.solarTip") : $t("system.homeTip") }}
              </div>
            </div>
          </div>
          <div v-if="isShowBattery" class="batteryPower">
            <div class="item">
              <div class="power">
                {{ handler().formatterNum(batGridOutput).split(" ")[0] }}
                {{ handler().formatterNum(batGridOutput).split(" ")[1] }}
              </div>
              <div class="text">
                {{ $t("energy.entLaden") }}
              </div>
              <div
                class="icon"
                @click.stop="
                  isShowBatteryOutputTip = !isShowBatteryOutputTip;
                  isShowBatteryInputTip = false;
                "
              >
                <img :src="'energy/ic_tip.png' | formatterPic" alt="" />
                <div class="bubble-tail" v-if="isShowBatteryOutputTip" />
              </div>
              <div class="bubble" v-if="isShowBatteryOutputTip">
                <div class="bubble-content">
                  {{ $t("system.batteryOutputTip") }}
                </div>
              </div>
            </div>
            <div class="item">
              <div class="power">
                {{ handler().formatterNum(batGridInput).split(" ")[0] }}
                {{ handler().formatterNum(batGridInput).split(" ")[1] }}
              </div>
              <div class="text">
                {{ $t("energy.laden") }}
              </div>
              <div
                class="icon"
                @click.stop="
                  isShowBatteryInputTip = !isShowBatteryInputTip;
                  isShowBatteryOutputTip = false;
                "
              >
                <img :src="'energy/ic_tip.png' | formatterPic" alt="" />
                <div class="bubble-tail" v-if="isShowBatteryInputTip" />
              </div>
              <div class="bubble" v-if="isShowBatteryInputTip">
                <div class="bubble-content">
                  {{ $t("system.batteryInputTip") }}
                </div>
              </div>
            </div>
          </div>
          <div v-if="isShowGrid" class="batteryPower">
            <div class="item">
              <div class="power">
                {{
                  handler()
                    .formatterNum(gridFromGrid - gridToGrid)
                    .split(" ")[0]
                }}
                {{
                  handler()
                    .formatterNum(gridFromGrid - gridToGrid)
                    .split(" ")[1]
                }}
              </div>
              <div class="text">
                {{ $t("system.fromGridInput") }}
              </div>
              <div
                class="icon"
                @click.stop="isShowGridInputTip = !isShowGridInputTip"
              >
                <img :src="'energy/ic_tip.png' | formatterPic" alt="" />
                <div class="bubble-tail" v-if="isShowGridInputTip" />
              </div>
              <div class="bubble" v-if="isShowGridInputTip">
                <div class="bubble-content">
                  {{ $t("system.gridTip") }}
                </div>
              </div>
            </div>
            <!--<div class="item">
                <div class="power">
                  {{ handler().formatterNum(gridToGrid).split(' ')[0] }}
                  {{ handler().formatterNum(gridToGrid).split(' ')[1] }}
                </div>
                <div class="text">
                  To Grid
                </div>
                <div class="icon" @click="isShowGridOutputTip = !isShowGridOutputTip">
                  <img :src="'energy/ic_tip.png' | formatterPic" alt="">
                  <div class="bubble" v-if="isShowGridOutputTip">
                    <div class="bubble-content">
                      The statistics are based on the total amount of electricity input into the battery through the AC charging port after the system enters surplus mode.
                    </div>
                    <div class="bubble-tail"/>
                  </div>
                </div>
              </div>-->
          </div>
        </div>
        <div class="home-bar" v-show="isShowHome && isShowPlugItem">
          <div
            class="home-item"
            :class="{
              active: $store.state.currentTheme === 'dark' && showAllCon,
              activeLight: $store.state.currentTheme !== 'dark' && showAllCon,
            }"
            @click="
              showOneCon = false;
              showTwoCon = false;
              showAllCon = true;
              network().getSolarFlowAllList();
            "
          >
            {{ $t("system.all") }}
          </div>
          <div
            class="home-item"
            :class="{
              active: $store.state.currentTheme === 'dark' && showOneCon,
              activeLight: $store.state.currentTheme !== 'dark' && showOneCon,
            }"
            @click="
              showOneCon = true;
              showTwoCon = false;
              showAllCon = false;
              network().getSolarFlowAllList();
            "
          >
            {{ $t("system.onGrid") }}
          </div>
          <div
            class="home-item"
            :class="{
              active: $store.state.currentTheme === 'dark' && showTwoCon,
              activeLight: $store.state.currentTheme !== 'dark' && showTwoCon,
            }"
            @click="
              showOneCon = false;
              showTwoCon = true;
              showAllCon = false;
              network().getSolarFlowAllList();
            "
          >
            {{ $t("system.offGrid") }}
          </div>
        </div>
        <div class="line-container" v-show="isShowSolar && pvList.length > 0">
          <div class="left">
            <div class="line-list">
              <!--            <div line="" class="item" :class="{'active' : currentSelect === ''}" @click="onSelectAll">ALL</div>-->
              <div
                :line="index"
                v-for="(item, index) in pvList"
                @click="onSelectPv(item, index)"
                :class="{
                  active:
                    $store.state.currentTheme === 'dark' &&
                    currentSelect == item.pvIndex,
                  activeLight:
                    $store.state.currentTheme !== 'dark' &&
                    currentSelect == item.pvIndex,
                }"
                class="item"
              >
                {{ item.pvName }}
              </div>
            </div>
          </div>
          <div class="right" @click="onAppSelectModal()">
            <div class="item">
              <img :src="'energy/small_right@2x.png' | formatterPic" alt="" />
            </div>
          </div>
        </div>
        <div class="ac-container">
          <div
            class="echart-title-top"
            v-show="isShowBattery && !isLoading && !isNothing"
          >
            {{ $t("energy.entLaden") }}
          </div>
          <div
            class="echart-title-bottom"
            v-show="
              isShowBattery && isShowBatteryLaden && !isLoading && !isNothing
            "
          >
            {{ $t("energy.laden") }}
          </div>
          <div
            class="echart-title-top"
            v-show="isShowGrid && !isLoading && !isNothing"
          >
            {{ $t("system.fromGrid") }}
          </div>
          <div
            class="echart-title-bottom"
            v-show="
              isShowGrid && grid1Output.length > 0 && !isLoading && !isNothing
            "
          >
            {{ $t("system.toGrid") }}
          </div>
          <canvas
            id="ac"
            class="ac-chart"
            @touchstart="handler().touchStart($event)"
            @touchmove="handler().touchMove($event)"
            @touchend="handler().touchEnd($event)"
            @error="error"
          ></canvas>
          <!--        <div class="cover" v-if="isShowCover" @longpress="isShowCover = false" @click="onCloseCover" @touchmove="isShowCover = false"/>-->
          <div v-show="isNothing" class="no-data">
            <img :src="'nothing.png' | formatterPic" alt="" />
            <div class="text">{{ $t("energy.nothing") }}</div>
          </div>
        </div>
        <div class="current-time">
          <div class="icon" @click="onTimeAction('previous')">
            <img :src="'energy/previous@2x.png' | formatterPic" alt="" />
          </div>
          <div class="text" @click="onTimeAction('all')">
            {{ currentTime }}
          </div>
          <div class="icon" @click="onTimeAction('next')">
            <img :src="'energy/next@2x.png' | formatterPic" alt="" />
          </div>
        </div>
        <div class="info-container" v-if="isShowSolar && !queryData.pvCircuit">
          <div class="header">
            <div class="left">{{ $t("system.energyDisSolar") }}</div>
          </div>
          <div class="total">
            {{ $t("energy.total") }} {{ handler().formatterNum(solarTotal) }}
          </div>
          <div class="line">
            <div
              class="line-active home"
              :style="
                'width:' + handler().formatterPro(solarToHome, solarTotal) + '%'
              "
            ></div>
            <div
              class="line-active storage"
              :style="
                'width:' +
                handler().formatterPro(solarToStorage, solarTotal) +
                '%'
              "
            ></div>
            <!--          <div class="line-active grid" :style="'width:'+handler().formatterPro(gridTotal, solarFlowTotal)+'%'"></div>-->
          </div>
          <div class="total-info">
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_home_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.toHome") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(solarToHome) }}
                </div>
                <div class="schedule">
                  {{ handler().formatterPro(solarToHome, solarTotal) }}%
                </div>
              </div>
            </div>
            <div class="item" v-if="solarToStorage > 0">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_battery_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.toStorage") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(solarToStorage) }}
                </div>
                <div class="schedule">
                  {{ handler().formatterPro(solarToStorage, solarTotal) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="info-container" v-if="isShowHome">
          <div class="header">
            <div class="left">{{ $t("system.energyDisHome") }}</div>
            <!--          <div class="right">-->
            <!--            Total {{ handler().formatterNum(homeTotal)}}-->
            <!--          </div>-->
          </div>
          <div class="total">
            {{ $t("energy.total") }} {{ handler().formatterNum(homeTotal) }}
          </div>
          <div class="line">
            <div
              class="line-active solar"
              :style="
                'width:' +
                handler().formatterPro(homeFromSolar, homeTotal) +
                '%'
              "
            ></div>
            <div
              class="line-active storage"
              :style="
                'width:' +
                handler().formatterPro(homeFromStorage, homeTotal) +
                '%'
              "
            ></div>
            <div
              class="line-active grid"
              :style="
                'width:' + handler().formatterPro(homeFromGrid, homeTotal) + '%'
              "
            ></div>
          </div>
          <div class="total-info">
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_solar_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.fromSolar") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(homeFromSolar) }}
                </div>
                <div class="schedule">
                  {{ handler().formatterPro(homeFromSolar, homeTotal) }}%
                </div>
              </div>
            </div>
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_battery_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.fromStorage") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(homeFromStorage) }}
                </div>
                <div class="schedule">
                  {{ handler().formatterPro(homeFromStorage, homeTotal) }}%
                </div>
              </div>
            </div>
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_grid_light.png' | formatterPic"
                  alt=""
                />{{ $t("ct.fromGrid") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(homeFromGrid) }}
                </div>
                <div class="schedule">
                  {{ handler().formatterPro(homeFromGrid, homeTotal) }}%
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="info-container" v-if="isShowBattery">
          <div class="batter-item">
            <div class="batter-header">
              {{ $t("energy.entLaden") }}
            </div>
            <div class="total-info">
              <div class="item border">
                <div class="left">
                  <img
                    class="radio"
                    :src="'energy/ic_home_light.png' | formatterPic"
                    alt=""
                  />
                  {{ $t("system.toHome") }}
                </div>
                <div class="right">
                  {{ handler().formatterNum(batToHome) }}
                </div>
              </div>
            </div>
          </div>
          <div class="batter-item">
            <div class="batter-header">
              {{ $t("energy.laden") }}
            </div>
            <div class="total-info">
              <div class="item" style="padding-bottom: unset">
                <div class="left">
                  <img
                    class="radio"
                    :src="'energy/ic_solar_light.png' | formatterPic"
                    alt=""
                  />
                  {{ $t("system.fromSolar") }}
                </div>
                <div class="right">
                  {{ handler().formatterNum(batFromStorage) }}
                </div>
              </div>
              <div class="item" style="padding-bottom: unset">
                <div class="left">
                  <img
                    class="radio"
                    :src="'energy/ic_grid_light.png' | formatterPic"
                    alt=""
                  />
                  {{ $t("system.fromGrid") }}
                </div>
                <div class="right">
                  {{ handler().formatterNum(batFromGrid) }}
                </div>
              </div>
              <!--<div class="item" style="padding-bottom: unset">
                  <div class="left">
                    <img class="radio" :src="'energy/ic_solar_light.png' | formatterPic" alt="">
                    From Other solar system
                  </div>
                  <div class="right">
                    {{ handler().formatterNum(fromSolar) }}
                  </div>
                </div>-->
            </div>
          </div>
        </div>
        <div class="info-container" v-if="isShowGrid">
          <div class="header">
            <div class="left">{{ $t("system.gridTotalText") }}</div>
          </div>
          <div class="total-info">
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_grid_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.fromGrid") }}
              </div>
              <div class="right">
                <div class="num">
                  {{ handler().formatterNum(gridFromGrid) }}
                </div>
              </div>
            </div>
            <div class="item">
              <div class="left">
                <img
                  class="radio"
                  :src="'energy/ic_grid_light.png' | formatterPic"
                  alt=""
                />{{ $t("system.toGrid") }}
              </div>
              <div class="right">
                <div class="num">-{{ handler().formatterNum(gridToGrid) }}</div>
              </div>
            </div>
            <!--<div class="item">
                <div class="left">
                    <div class="radio storage"/>
                    <div class="text">
                      From Ohter Solar System
                      <img @click.stop="isShowTip = !isShowTip" :src="'energy/ic_tip.png' | formatterPic" alt="">
                      <div class="bubble" v-if="isShowTip">
                        <div class="bubble-content">
                          The statistics are based on the total amount of electricity input into the battery through the AC charging port after the system enters surplus mode.
                        </div>
                        <div class="bubble-tail"/>
                      </div>
                    </div>
                  </div>
                <div class="right">
                  <div class="num">
                    0.6 kWh
                  </div>
                </div>
              </div>-->
          </div>
        </div>
        <div
          class="sbv-container"
          v-show="isShowBattery && queryData.type === 0"
        >
          <div class="sbv-header">
            <div class="echarts-title">
              {{ $t("energy.battery") }}{{ $t("energy.chargeLevel") }}
            </div>
            <div class="sbv-ac">
              <canvas
                v-show="!isNothing2"
                id="sbv"
                class="ac-chart"
                @touchstart="handler().touchStarts($event)"
                @touchmove.prevent="handler().touchMoves($event)"
                @touchend="handler().touchEnds($event)"
                @error="error"
              ></canvas>
              <div v-show="isNothing2" class="no-data">
                <img :src="'nothing.png' | formatterPic" alt="" />
                <div class="text">{{ $t("energy.nothing") }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getSolarFlowList,
  getSolarFlowHemsElectricList,
  getSolarFlowPvList,
  getSolarFlowAllList,
  getCtHemsList,
} from "@/api/api";
import zendureModal from "@/components/zendure-modal";
import * as echarts from "@/static/echarts.min";
import { toFixed } from "@/utils";
import dayjs from "dayjs";

let acChart = null;
let sbvChart = null;

// pv线路设备类型
const pvTypeList = [{ type: 1 }, { type: 5 }, { type: 14 }, { type: 15 }];

export default {
  name: "system",
  components: {
    zendureModal,
  },
  data() {
    return {
      echarts,
      first: false,
      loop: null, // 定时器
      more: true, // 是否展示颗粒化选项
      isNothing: false,
      isNothing2: false,
      isLoading: false,
      isShowSolar: true,
      isShowHome: false,
      isShowGrid: false,
      isShowGridItem: true,
      isShowPlugItem: false,
      isShowBattery: false,
      currentTime: "", // 当前选取时间段
      isShowModel: false,
      currentSelect: 0,
      clientHeight: 0,
      observer: null,
      pvList: [],
      currentType: 0, // 默认颗粒度
      solarList: [],
      conList: [], // 家庭输出
      showAllCon: true,
      showOneCon: false,
      showTwoCon: false,
      //太阳能数据汇总
      solarTotal: 0,
      solarToHome: 0,
      solarToStorage: 0,

      //家庭数据汇总
      homeTotal: 0,
      homeFromSolar: 0,
      homeFromStorage: 0,
      homeFromGrid: 0,

      // 电池数据汇总
      batGridOutput: 0,
      batGridInput: 0,
      batToHome: 0,
      batFromStorage: 0,
      batFromGrid: 0,
      batFromOther: 0,
      isShowBatteryLaden: false, //是否显示电池负数
      //电网数据汇总
      gridToGrid: 0,
      gridFromGrid: 0,

      allData: [], // 保存默认进来全部数据
      // 电池输入输出
      input: [],
      output: [],
      batteryList: [],
      grid1Input: [],
      grid1Output: [],
      isShowSolarTip: false,
      isShowBatteryInputTip: false,
      isShowBatteryOutputTip: false,
      isShowGridInputTip: false,
      isShowGridOutputTip: false,
      queryData: {
        // zone: 'Europe/Berlin',
        // deviceId: '',
        // hemsId: 907,
        // beginDate: '2025-05-23',
        // endDate: '2025-05-23',
        // pvCircuit: 1,
        type: 0, //	type 0实时 1:天 2:周 3:月 4:年 5全生命
      },
    };
  },
  watch: {
    // isShowSolar(val) {
    //   if (val) {
    //     this.network().getSolarFlowAllList();
    //   }
    // }
  },
  mounted() {
    this.observeHeightChanges();
    // this.guide.guideText = this.$t('energy.guideText')
    // 初始化图表
    acChart = echarts.init(document.getElementById("ac"));
    sbvChart = echarts.init(document.getElementById("sbv"));

    // 监听图表缩放 取消tooltip
    acChart.on("datazoom", () => {
      this.isShowCover = false;
      this.handler().chartScroll();
    });
    sbvChart.on("datazoom", () => {
      this.isShowCover = false;
      this.handler().chartScroll();
    });
    acChart.getZr().on("mousedown", (params) => {
      this.loop = setTimeout(() => {
        this.loop = 0;
        this.isMove = true;
        var pointInPixel = [params.offsetX, params.offsetY];
        if (acChart.containPixel("grid", pointInPixel)) {
          var pointInGrid = acChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          );
          var xIndex = pointInGrid[0];
          acChart.dispatchAction({
            type: "showTip",
            x: pointInPixel[0],
            y: pointInPixel[1],
            dataIndex: xIndex,
          });
          acChart.setOption({
            dataZoom: {
              disabled: true,
            },
          });
          //业务代码
        }
      }, 200);
    });
    acChart.getZr().on("mousemove", (params) => {
      if (this.isMove) {
        var pointInPixel = [params.offsetX, params.offsetY];
        if (acChart.containPixel("grid", pointInPixel)) {
          var pointInGrid = acChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          );
          var xIndex = pointInGrid[0];
          acChart.dispatchAction({
            type: "showTip",
            x: pointInPixel[0],
            y: pointInPixel[1],
            dataIndex: xIndex,
          });
          //业务代码
        }
      }
    });
    sbvChart.getZr().on("mousedown", (params) => {
      this.loop = setTimeout(() => {
        this.loop = 0;
        this.isMove = true;
        var pointInPixel = [params.offsetX, params.offsetY];
        if (sbvChart.containPixel("grid", pointInPixel)) {
          var pointInGrid = sbvChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          );
          var xIndex = pointInGrid[0];
          sbvChart.dispatchAction({
            type: "showTip",
            x: pointInPixel[0],
            y: pointInPixel[1],
          });
          sbvChart.setOption({
            dataZoom: {
              disabled: true,
            },
          });
          //业务代码
        }
      }, 200);
    });
    sbvChart.getZr().on("mousemove", (params) => {
      if (this.isMove) {
        var pointInPixel = [params.offsetX, params.offsetY];
        if (sbvChart.containPixel("grid", pointInPixel)) {
          var pointInGrid = sbvChart.convertFromPixel(
            { seriesIndex: 0 },
            pointInPixel
          );
          var xIndex = pointInGrid[0];
          sbvChart.dispatchAction({
            type: "showTip",
            x: pointInPixel[0],
            y: pointInPixel[1],
          });
          //业务代码
        }
      }
    });
    // this.network().getSolarFlowAllList();
    // this.network().getSolarFlowPvList();
    // })
    // 挂载ios&安卓方法
    if (this.getEnv() === "android") {
      // window.android.loadFinished()
      // 获取选择的日期
      window.getSelectDate = (data) => {
        console.info(data, "参数");
        this.init(data);
      };
      // 获取选择pv线路下标
      window.getSelectPvIndex = (data) => {
        let { index } = data;
        console.info("app传参下标", index);
        if (index) {
          this.onSelectPv(this.pvList[index], index);
        } else {
          this.onSelectAll();
        }
        this.$nextTick(() => {
          const divVal = document.querySelector(
            `[self="${this.currentSelect}"]`
          ); // 使用self自定义属性跳转
          if (divVal) {
            divVal.scrollIntoView({ behavior: "smooth" });
          }
        });
      };
    } else if (this.getEnv() === "ios") {
      this.setupWebViewJavascriptBridge((bridge) => {
        bridge.callHandler("loadFinished");
      });

      this.setupWebViewJavascriptBridge((bridge) => {
        bridge.registerHandler("getSelectDate", (data) => {
          console.info(data, "参数");
          const item = JSON.parse(data);
          this.init(item);
        });
      });
      this.setupWebViewJavascriptBridge((bridge) => {
        bridge.registerHandler("getSelectPvIndex", (data) => {
          let { index } = data;
          console.info("app传参下标", index, this.pvList);
          if (index) {
            this.onSelectPv(this.pvList[index], index);
          } else {
            this.onSelectAll();
          }
          this.$nextTick(() => {
            const divVal = document.querySelector(
              `[self="${this.currentSelect}"]`
            ); // 使用self自定义属性跳转
            if (divVal) {
              divVal.scrollIntoView({ behavior: "smooth" });
            }
          });
        });
      });
    }
    acChart.on("legendselectchanged", (params) => {
      switch (params.name) {
        case this.$t("energy.solar"):
          this.isShowSolar = !this.isShowSolar;
          break;
        case this.$t("energy.con"):
          this.isShowHome = !this.isShowHome;
          break;
        case this.$t("energy.grid"):
          this.isShowSbv = !this.isShowSbv;
          break;
        case "PvHub Mini":
          this.isShowMini = !this.isShowMini;
          break;
        case "Hub 2000":
          this.isShowHub = !this.isShowHub;
          break;
      }
    });
  },
  methods: {
    restTip() {
      this.isShowSolarTip = false;
      this.isShowBatteryInputTip = false;
      this.isShowBatteryOutputTip = false;
      this.isShowGridInputTip = false;
      this.isShowGridOutputTip = false;
    },
    observeHeightChanges() {
      const observerOptions = {
        childList: true,
        subtree: true,
      };

      this.observer = new MutationObserver(() => {
        this.handler().updateContentHeight(); // 内容变化时更新高度
      });

      this.observer.observe(this.$refs.content, observerOptions);
    },
    init(item) {
      acChart.dispatchAction({
        type: "hideTip",
      });
      acChart.dispatchAction({
        type: "updateAxisPointer",
        currTrigger: "leave",
      });
      sbvChart.dispatchAction({
        type: "hideTip",
      });
      sbvChart.dispatchAction({
        type: "updateAxisPointer",
        currTrigger: "leave",
      });
      this.restData();
      acChart.clear();
      this.allData = [];
      this.isShowGridItem = item.isShowCT;
      this.isShowPlugItem = item.isShowPlug;
      this.queryData.hemsId = item.hemsId;
      if (!this.queryData.beginDate) {
        // 默认进来第一次没有时间拿app的
        this.queryData.beginDate = item.beginDate;
        this.queryData.endDate = item.endDate;
        this.currentTime =
          item.beginDate +
          (this.queryData.type === 0 ? "" : " ~ " + item.endDate);
      }
      if (item.isCalendar) {
        this.queryData.beginDate = item.beginDate;
        this.queryData.endDate = item.endDate;
        this.currentTime =
          item.beginDate +
          (this.queryData.type === 0 ? "" : " ~ " + item.endDate);
      }
      this.queryData.zone =
        item.zone || this.$store.state.zone || uni.getStorageSync("zone");
      // this.currentTime = this.queryData.beginDate;
      this.network().getSolarFlowPvList();

      if (this.isShowGrid) {
        this.network().getCtHemsList();
        return;
      }
      if (this.currentSelect > 0) {
        this.network().getSolarFlowList();
      } else {
        this.network().getSolarFlowAllList();
      }
      if (this.isShowBattery) {
        this.network().getSolarFlowHemsElectricList();
      }
      this.$forceUpdate();
    },
    onSelectAll() {
      this.currentSelect = 0;
      this.queryData.pvCircuit = "";
      this.queryData.deviceId = "";
      this.network().getSolarFlowAllList();
    },
    onAppSelectModal() {
      let data = { pvList: this.pvList, currentPvIndex: this.currentSelect };
      if (this.getEnv() === "android") {
        window.android.showPvModal(JSON.stringify(data));
      } else if (this.getEnv() === "ios") {
        this.setupWebViewJavascriptBridge((bridge) => {
          bridge.callHandler("showPvModal", data);
        });
      }
    },
    restData() {
      this.solarTotal = 0;
      this.solarToHome = 0;
      this.solarToStorage = 0;
      // 家庭数据汇总
      this.homeTotal = 0;
      this.homeFromSolar = 0;
      this.homeFromStorage = 0;
      this.homeFromGrid = 0;
      // 电池数据汇总
      this.batGridOutput = 0;
      this.batGridInput = 0;
      this.batToHome = 0;
      this.batFromStorage = 0;
      this.batFromGrid = 0;
      this.batFromOther = 0;
      // 电网数据汇总
      this.gridToGrid = 0;
      this.gridFromGrid = 0;
    },
    onTimeAction(dateType) {
      //dateType = previous next all
      if (dateType === "all") {
        let data = {
          dateType,
          type: this.currentType,
          beginDate: this.queryData.beginDate,
          endDate: this.queryData.endDate,
        };
        if (this.getEnv() === "android") {
          window.android.timeAction(JSON.stringify(data));
        } else if (this.getEnv() === "ios") {
          this.setupWebViewJavascriptBridge((bridge) => {
            bridge.callHandler("timeAction", data);
          });
        }
      } else {
        this.allData = [];
        acChart.clear();
        this.restData();
        switch (this.currentType) {
          case 0:
            const day = this.handler().navigateTime("day", dateType);
            this.queryData.beginDate = day.startOf("day").format("YYYY-MM-DD");
            this.queryData.endDate = day.endOf("day").format("YYYY-MM-DD");
            this.currentTime = `${this.queryData.beginDate}`;
            break;
          case 2:
            const week = this.handler().navigateTime("week", dateType);
            this.queryData.beginDate = week
              .startOf("week")
              .format("YYYY-MM-DD");
            this.queryData.endDate = week.endOf("week").format("YYYY-MM-DD");
            this.currentTime = `${this.queryData.beginDate} ~ ${this.queryData.endDate}`;
            break;
          case 3:
            const month = this.handler().navigateTime("month", dateType);
            this.queryData.beginDate = month
              .startOf("month")
              .format("YYYY-MM-DD");
            this.queryData.endDate = month.endOf("month").format("YYYY-MM-DD");
            this.currentTime = `${month.format("YYYY-MM")}`;
            break;
          case 4:
            const year = this.handler().navigateTime("year", dateType);
            this.queryData.beginDate = year
              .startOf("year")
              .format("YYYY-MM-DD");
            this.queryData.endDate = year.endOf("year").format("YYYY-MM-DD");
            this.currentTime = `${year.format("YYYY")}`;
            break;
        }
        if (this.currentSelect > 0) {
          this.network().getSolarFlowList();
        } else {
          if (this.isShowGrid) {
            this.network().getCtHemsList();
            return;
          }
          this.network().getSolarFlowAllList();
        }
        if (this.isShowBattery) {
          this.network().getSolarFlowHemsElectricList();
        }
      }
    },
    onSelectPv(item, index) {
      if (item.pvIndex > 0) {
        this.allData = [];
        this.currentSelect = index;
        this.queryData.pvCircuit = item.type;
        this.queryData.deviceId = item.deviceId;
        this.network().getSolarFlowList();
      } else {
        this.currentSelect = 0;
        this.queryData.pvCircuit = "";
        this.queryData.deviceId = "";
        this.network().getSolarFlowAllList();
      }
      this.$forceUpdate();
    },
    onChangeType(type) {
      if (this.isLoading) return;
      acChart.clear();
      this.restData();
      acChart.dispatchAction({
        type: "hideTip",
      });
      acChart.dispatchAction({
        type: "updateAxisPointer",
        currTrigger: "leave",
      });
      this.currentType = type;
      switch (type) {
        case 0:
          const today = dayjs();
          this.handler().setDates(today, today, 0);
          break;
        case 2:
          this.handler().setDates(
            dayjs().startOf("week").add(0, "day"),
            dayjs().endOf("week").add(0, "day"),
            1
          );
          break;
        case 3:
          this.handler().setDates(
            dayjs().startOf("month"),
            dayjs().endOf("month"),
            1
          );
          break;
        case 4:
          this.handler().setDates(
            dayjs().startOf("year"),
            dayjs().endOf("year"),
            3
          );
          break;
      }
      // 切换颗粒度的时候清空缓存
      this.allData = [];
      if (this.isShowGrid) {
        this.network().getCtHemsList();
        return;
      }
      if (this.currentSelect > 0) {
        this.network().getSolarFlowList();
      } else {
        this.network().getSolarFlowAllList();
      }
      if (this.isShowBattery) {
        this.network().getSolarFlowHemsElectricList();
      }
      this.$forceUpdate();
    },
    onSelectDate() {
      if (this.isLoading) return;
      if (this.getEnv() === "android") {
        window.android.selectDate();
      } else if (this.getEnv() === "ios") {
        this.setupWebViewJavascriptBridge((bridge) => {
          bridge.callHandler("selectDate");
        });
      }
    },
    restSelect(type) {
      acChart.clear();
      this.restTip();
      this.isShowSolar = false;
      this.isShowBattery = false;
      this.isShowHome = false;
      this.isShowGrid = false;
      this.currentSelect = 0;
      this.showAllCon = true;
      this.showOneCon = false;
      this.showTwoCon = false;
      this.queryData.pvCircuit = "";
      this.queryData.deviceId = "";

      this[type] = true;
      if (this.isShowBattery) {
        this.network().getSolarFlowHemsElectricList();
      }
      this.network().getSolarFlowAllList();

      if (this.isShowGrid) {
        this.network().getCtHemsList();
      }
    },
    network() {
      return {
        getSolarFlowList: async () => {
          this.isNothing = false;
          this.isLoading = true;
          acChart.showLoading({
            text: "",
            color: "#00A180",
            textColor: "#000",
            maskColor: "transparent",
            zlevel: 0,
            lineWidth: 3,
          });
          const { data } = await getSolarFlowList(this.queryData);
          let list = [];
          if (
            JSON.stringify(data) == "{}" ||
            JSON.stringify(data.data) == "{}"
          ) {
            this.isNothing = true;
            this.restData();
          } else {
            // 太阳能
            this.solarTotal = data.solar + data.socketInputTotal;
            let batteryInput = data.batteryOutput;
            let gridInputTotal = data.gridInputTotal;
            this.solarToStorage =
              batteryInput - gridInputTotal < 0
                ? 0
                : batteryInput - gridInputTotal;
            this.solarToHome =
              this.solarTotal - this.solarToStorage < 0
                ? 0
                : this.solarTotal - this.solarToStorage;
            this.isNothing = false;
            //获取时间轴
            list = this.handler().formatterDate(
              this.handler().aggregate5MinData(data.data[1])
            );
            console.info(list);
            this.solarList = this.handler().getDates(
              this.handler().aggregate5MinData(
                data.data[this.queryData.pvCircuit]
              )
            );
            acChart.hideLoading();
          }

          const richCss = {
            start: { width: 60, align: "right" },
            end: { width: 60, align: "left" },
          };
          const option = {
            dataZoom: {
              type: "inside",
              minSpan: this.queryData.type === 0 ? 5 : 30,
              preventDefaultMouseMove: false,
            },
            tooltip: {
              extraCssText: "border-radius: 10px",
              backgroundColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              borderColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              triggerOn: "none",
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // 获取容器宽度
                const containerWidth = acChart.getWidth();

                // 根据触发点的横坐标位置决定tooltip应该显示在左侧还是右侧
                const tooltipWidth = dom.offsetWidth;
                const posX =
                  point[0] + tooltipWidth > containerWidth
                    ? point[0] - tooltipWidth - 10
                    : point[0] + 10;
                // 固定在顶部
                return [posX, "0"];
              },
              confine: true,
              axisPointer: {
                z: 1,
                type: "line",
                lineStyle: {
                  width: 1,
                  type: "dashed",
                  color: this.handler().getLineColor(),
                },
              },
              show: true,
              formatter: (params) => {
                let htmls = "";
                let text = "";
                params.forEach((v, i) => {
                  let sub = "";
                  text = this.powerDisplay(v.value, this.queryData.type) || 0;
                  if (
                    (v.seriesIndex === 2 || v.seriesIndex === 3) &&
                    v.value !== 0
                  ) {
                    sub = `(${
                      v.value > 0
                        ? this.$t("energy.entLaden")
                        : this.$t("energy.laden")
                    })`;
                  }
                  htmls += `
                            <div class="chart-tip">
                              <div class="input">
                                  <div class="tips-item">
                                      <span class="circle" style="${
                                        "background:" + v.color
                                      }"></span> ${text} ${v.seriesName} ${sub}
                                  </div>
                              </div>
                          </div>`;
                });
                return (htmls += `<div class="time-charts">
                                  ${params[0].name}
                              </div>`);
              },
            },
            legend: {
              show: false,
              icon: "circle",
              type: "plain",
              itemWidth: 12,
              itemHeight: 12,
              bottom: 12,
            },
            xAxis: {
              type: "category",
              boundaryGap: true,
              data: list,
              axisLabel: {
                showMinLabel: true,
                showMaxLabel: true,
                margin: 14,
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (val, i) => {
                  if (this.queryData.type !== 0) return val;
                  if (i === 0) {
                    return `{start| ${val}}`;
                  }
                  if (i === length) {
                    console.info("进来了");
                    return `{end| ${val}}`;
                  }
                  return val;
                },
                rich: richCss,
              },
              axisTick: {
                show: false,
                alignWithLabel: true,
              },
              axisLine: {
                show: true,
                // onZero: false,
                lineStyle: {
                  type: "dashed",
                  color: "#616161",
                  width: "1",
                },
              },
            },
            yAxis: {
              position: "right",
              type: "value",
              show: true,
              splitNumber: 2,
              splitLine: {
                show: true,
                lineStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(255,255,255,0.15)"
                      : "rgba(204,204,204,0.2)",
                  type: "dashed",
                },
              },
              axisLabel: {
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (v, i) => {
                  let max = acChart.getModel().getComponent("yAxis").axis.scale
                    ._extent[1];
                  let maxLabel = this.powerDisplay(v, this.queryData.type);
                  let maxUnit = this.powerDisplay(
                    max,
                    this.queryData.type
                  ).split(" ")[1];
                  if (v === 0) {
                    return v;
                  }
                  if (v !== max) {
                    if (maxUnit === maxLabel.split(" ")[1]) {
                      return maxLabel.split(" ")[0];
                    }
                    return maxLabel;
                  } else {
                    return maxLabel;
                  }
                },
              },
            },
            series: [
              {
                name: this.$t("energy.solar"),
                data: this.solarList,
                type: this.queryData.type === 0 ? "line" : "bar",
                showSymbol: false,
                smooth: true,
                areaStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(252,183,107,0.35)"
                      : "rgba(255,154,0,0.14)",
                },
                lineStyle: {
                  join: "round",
                  cap: "round",
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#FCB76B"
                      : "#FF9A00", //折线颜色
                  width: 1,
                },
                itemStyle: {
                  borderWidth: 2,
                  borderRadius: 14,
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#FCB76B"
                      : "#FF9A00", //折线颜色
                },
              },
            ],
            grid: [
              {
                top: "10",
                left: "10px",
                right: "8px",
                bottom: "0",
                containLabel: true,
              },
            ],
          }; // ECharts 配置项

          acChart.setOption(option);
          acChart.resize();
          this.isLoading = false;
        },
        getSolarFlowAllList: async () => {
          this.isNothing = false;
          this.isLoading = true;
          acChart.showLoading({
            text: "",
            color: "#00A180",
            textColor: "#000",
            maskColor: "transparent",
            zlevel: 0,
            lineWidth: 3,
          });
          // 有则先拿缓存
          let data;
          if (this.allData.length > 0) {
            data = this.allData;
          } else {
            const response = await getSolarFlowAllList(this.queryData);
            data = response.data;
          }
          let list = [];
          let length = 0;
          let jsonData = data.filter(
            (item) => JSON.stringify(item.data) !== "{}"
          );
          if (jsonData.length === 0) {
            this.isNothing = true;
            this.restData();
          } else {
            // 每次全部默认保存所有数据
            if (this.currentSelect == 0) {
              console.info("进来没");
              this.allData = data;
            } else {
              this.allData = [];
            }
            // 太阳能
            let solarTotal = data
              .map((item) => item.solar)
              .reduce((accum, curr) => accum + curr, 0);
            // 离网输入
            let socketInputTotal = data
              .map((item) => item.socketInputTotal)
              .reduce((accum, curr) => accum + curr, 0);
            this.solarTotal = solarTotal + socketInputTotal; // 太阳能加上离网输入
            let batteryInput = data
              .map((item) => item.batteryOutput)
              .reduce((accum, curr) => accum + curr, 0);
            let gridInputTotal = data
              .map((item) => item.gridInputTotal)
              .reduce((accum, curr) => accum + curr, 0);
            let socketOutputTotal = data
              .map((item) => item.socketOutputTotal)
              .reduce((accum, curr) => accum + curr, 0); // 12
            let gridDirectTotal = data
              .map((item) => item.gridDirectTotal)
              .reduce((accum, curr) => accum + curr, 0); // 16
            this.solarToStorage =
              batteryInput - gridInputTotal < 0
                ? 0
                : batteryInput - gridInputTotal;
            this.solarToHome =
              this.solarTotal - this.solarToStorage < 0
                ? 0
                : this.solarTotal - this.solarToStorage;
            // 电池
            this.batToHome = data
              .map((item) => item.batteryInput)
              .reduce((accum, curr) => accum + curr, 0);
            this.batFromGrid =
              data
                .map((item) => item.gridInputTotal)
                .reduce((accum, curr) => accum + curr, 0) -
                socketOutputTotal <
              0
                ? 0
                : data
                    .map((item) => item.gridInputTotal)
                    .reduce((accum, curr) => accum + curr, 0) -
                  socketOutputTotal;
            this.batGridOutput = data
              .map((item) => item.batteryInput)
              .reduce((accum, curr) => accum + curr, 0);
            this.batFromStorage =
              this.solarToStorage < 0 ? 0 : this.solarToStorage;
            this.batGridInput = this.batFromStorage + this.batFromGrid;
            //家庭
            let homeTotal = data
              .map((item) => item.home)
              .reduce((accum, curr) => accum + curr, 0); // 家庭总消耗+电网直通
            this.homeTotal = homeTotal + socketOutputTotal;
            this.homeFromSolar = this.solarToHome;
            let diff = this.homeFromSolar - this.homeTotal;
            this.homeTotal = diff > 0 ? this.homeTotal + diff : this.homeTotal;
            this.homeFromStorage = this.batGridOutput;

            // 太阳能1+5
            let solar1 = this.handler().formatterArrayData(data, 1, 5);
            let solar2 = this.handler().formatterArrayData(data, 14, 15);
            let socketInput = this.handler().formatterArrayData(data, 13); // 离网输入总
            let solarTotals = solar1.map(
              (item, index) => item + (solar2[index] || 0)
            );
            this.solarList = solarTotals.map(
              (item, index) => item + (socketInput[index] || 0)
            );

            if (this.isShowBattery) {
              this.input = this.handler().formatterArrayData(data, 2, 7); // 2+7
              let output = this.handler().formatterArrayData(data, 4, 8); // 4 + 8
              this.output = output.map((item) => 0 - item);
              let arr = [];
              this.solarList.forEach((item, index) => {
                if (this.input[index] > 0) {
                  if (this.input[index] > Math.abs(this.output[index] || 0)) {
                    arr.push(this.input[index] || 0);
                  } else {
                    arr.push(this.output[index] || 0);
                  }
                } else {
                  arr.push(this.output[index] || 0);
                }
              });
              this.batteryList = arr;
              this.isShowBatteryLaden = this.batteryList.some((num) => num < 0);
              if (this.queryData.type !== 0) {
                if (this.input.length === 0 && this.output.length === 0) {
                  this.isNothing = true;
                  return;
                }
              } else {
                let sum = this.batteryList
                  .map((item) => item)
                  .reduce((accum, curr) => accum + curr, 0);
                if (sum === 0) {
                  this.isNothing = true;
                  return;
                }
              }
            }
            if (this.isShowHome) {
              if (this.isShowGridItem) {
                await this.network().getCtHemsList("home");
              }
              let allList = this.handler().formatterArrayData(data, 3, 12);
              let onGridList = this.handler().formatterArrayData(data, 3);
              let offGridList = this.handler().formatterArrayData(data, 12);
              if (!this.isShowGridItem) {
                this.homeFromGrid =
                  this.homeTotal - this.homeFromSolar - this.homeFromStorage < 0
                    ? 0
                    : this.homeTotal -
                      this.homeFromSolar -
                      this.homeFromStorage;
              }
              if (this.showAllCon) {
                this.conList = allList;
              } else if (this.showOneCon) {
                this.conList = onGridList;
              } else {
                this.conList = offGridList;
              }
              if (this.conList.length === 0) {
                acChart.clear();
                this.isNothing = true;
                return;
              }
            }
            let time = data.filter(
              (item) => JSON.stringify(item.data) !== "{}"
            );
            list = this.handler().formatterDate(
              this.handler().aggregate5MinData(time[0].data[1])
            );
            console.info(this.currentType, list, "----------");
            this.isNothing = false;
            length = list.length - 1;
            //获取时间轴
            // list = this.handler().formatterDate(data.data[1])
            acChart.hideLoading();
          }

          const richCss = {
            start: { width: 60, align: "right" },
            end: { width: 60, align: "left" },
          };
          const option = {
            dataZoom: {
              type: "inside",
              minSpan: this.queryData.type === 0 ? 5 : 30,
              preventDefaultMouseMove: false,
            },
            tooltip: {
              extraCssText: "border-radius: 10px",
              backgroundColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              borderColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              triggerOn: "none",
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // 获取容器宽度
                const containerWidth = acChart.getWidth();

                // 根据触发点的横坐标位置决定tooltip应该显示在左侧还是右侧
                const tooltipWidth = dom.offsetWidth;
                const posX =
                  point[0] + tooltipWidth > containerWidth
                    ? point[0] - tooltipWidth - 10
                    : point[0] + 10;
                // 固定在顶部
                return [posX, "0"];
              },
              confine: true,
              axisPointer: {
                z: 1,
                type: "line",
                lineStyle: {
                  width: 1,
                  type: "dashed",
                  color: this.handler().getLineColor(),
                },
              },
              show: true,
              formatter: (params) => {
                let htmls = "";
                let text = "";
                params.forEach((v, i) => {
                  let sub = "";
                  text = this.powerDisplay(v.value, this.queryData.type) || 0;
                  if (this.isShowBattery && v.value !== 0) {
                    sub = `${
                      v.value > 0
                        ? this.$t("energy.entLaden")
                        : this.$t("energy.laden")
                    }`;
                  }
                  htmls += `
                            <div class="chart-tip">
                              <div class="input">
                                  <div class="tips-item">
                                      <span class="circle" style="${
                                        "background:" + v.color
                                      }"></span> ${text} ${v.seriesName} ${sub}
                                  </div>
                              </div>
                          </div>`;
                });
                return (htmls += `<div class="time-charts">
                                  ${params[0].name}
                              </div>`);
              },
            },
            legend: {
              show: false,
              icon: "circle",
              type: "plain",
              itemWidth: 12,
              itemHeight: 12,
              bottom: 12,
            },
            xAxis: {
              type: "category",
              boundaryGap: true,
              data: list,
              axisLabel: {
                showMinLabel: true,
                showMaxLabel: true,
                margin: 14,
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (val, i) => {
                  if (this.queryData.type !== 0) return val;
                  if (i === 0) {
                    return `{start| ${val}}`;
                  }
                  if (i === length) {
                    console.info("进来了");
                    return `{end| ${val}}`;
                  }
                  return val;
                },
                rich: richCss,
              },
              axisTick: {
                show: false,
                // alignWithLabel: true
              },
              axisLine: {
                show: true,
                // onZero: false,
                lineStyle: {
                  type: "dashed",
                  color: "#616161",
                  width: "1",
                },
              },
            },
            yAxis: {
              position: "right",
              type: "value",
              show: true,
              splitNumber: 2,
              splitLine: {
                show: true,
                lineStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(255,255,255,0.15)"
                      : "rgba(204,204,204,0.2)",
                  type: "dashed",
                },
              },
              axisLabel: {
                align: "left",
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (v, i) => {
                  let max = acChart.getModel().getComponent("yAxis").axis.scale
                    ._extent[1];
                  let maxLabel = this.powerDisplay(v, this.queryData.type);
                  let maxUnit = this.powerDisplay(
                    max,
                    this.queryData.type
                  ).split(" ")[1];
                  if (v === 0) {
                    return v;
                  }
                  if (v !== max) {
                    if (maxUnit === maxLabel.split(" ")[1]) {
                      return maxLabel.split(" ")[0];
                    }
                    return maxLabel;
                  } else {
                    return maxLabel;
                  }
                },
              },
            },
            series: this.isShowSolar
              ? [
                  {
                    barWidth: "30%",
                    name: this.$t("energy.solar"),
                    data: this.solarList,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    showSymbol: false,
                    smooth: true,
                    areaStyle: {
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(252,183,107,0.35)"
                          : "rgba(255,154,0,0.14)",
                    },
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#FCB76B"
                          : "#FF9A00", //折线颜色
                      width: 1,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#FCB76B"
                          : "#FF9A00", //折线颜色
                    },
                  },
                ]
              : this.isShowBattery
              ? [
                  {
                    barWidth: "30%",
                    stack: "total",
                    name: "",
                    data:
                      this.queryData.type === 0 ? this.batteryList : this.input,
                    smooth: true,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    areaStyle: {
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(1,242,207,0.14)"
                          : "rgba(0,161,128,0.5)",
                    },
                    showSymbol: false,
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#01F2CF"
                          : "rgba(0,161,128,0.8)", //折线颜色
                      width: 1,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#01F2CF"
                          : "#00A180", //折线颜色
                    },
                  },
                  {
                    barWidth: "30%",
                    stack: "total",
                    name: "",
                    data: this.queryData.type === 0 ? [] : this.output,
                    smooth: true,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    areaStyle: {
                      color: "rgba(0,161,128,0.5)",
                    },
                    showSymbol: false,
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(1,242,207,0.5)"
                          : "rgba(0,161,128,0.8)", //折线颜色
                      width: 2,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(1,242,207,0.5)"
                          : "#00A180", //折线颜色
                    },
                  },
                ]
              : this.isShowHome
              ? [
                  {
                    barWidth: "30%",
                    name: this.$t("energy.con"),
                    data: this.conList,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    smooth: true,
                    areaStyle: {
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(51,175,255,0.14)"
                          : "rgba(51,175,255,0.5)",
                    },
                    showSymbol: false,
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      // shadowColor: '#33AFFF',
                      // shadowBlur: 10,
                      // shadowOffsetY: 4,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#33AFFF"
                          : "rgba(51,175,255,0.8)", //折线颜色
                      width: 1,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#06C1FF"
                          : "#33AFFF", //折线颜色
                    },
                  },
                ]
              : [
                  {
                    barWidth: "30%",
                    stack: "total",
                    name: `输入`,
                    data: this.grid1Input,
                    smooth: true,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    areaStyle: {
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(224,224,224,0.14)"
                          : "rgba(117,117,117,0.5)",
                    },
                    showSymbol: false,
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#E0E0E0"
                          : "rgba(117,117,117,0.8)", //折线颜色
                      width: 1,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "#E0E0E0"
                          : "#757575", //折线颜色
                    },
                  },
                  {
                    barWidth: "30%",
                    stack: "total",
                    name: `输出`,
                    data: this.grid1Output,
                    smooth: true,
                    type: this.queryData.type === 0 ? "line" : "bar",
                    areaStyle: {
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(224,224,224,0.14)"
                          : "rgba(117,117,117,0.5)",
                    },
                    showSymbol: false,
                    lineStyle: {
                      join: "round",
                      cap: "round",
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(224,224,224,0.5)"
                          : "rgba(117,117,117,0.8)", //折线颜色
                      width: 1,
                    },
                    itemStyle: {
                      borderWidth: 2,
                      borderRadius: 14,
                      color:
                        this.$store.state.currentTheme === "dark"
                          ? "rgba(224,224,224,0.5)"
                          : "#757575", //折线颜色
                    },
                  },
                ],
            grid: [
              {
                top: "10",
                left: "10px",
                right: "8px",
                bottom: "0",
                containLabel: true,
              },
            ],
          }; // ECharts 配置项

          acChart.setOption(option);
          acChart.resize();
          this.isLoading = false;
        },
        getSolarFlowHemsElectricList: async () => {
          this.isNothing2 = false;
          this.isLoading = true;
          sbvChart.showLoading({
            text: "",
            color: "#00A180",
            textColor: "#000",
            maskColor: "transparent",
            zlevel: 0,
            lineWidth: 3,
          });
          const { data } = await getSolarFlowHemsElectricList(this.queryData);
          let list = [];
          let inputList = [];
          let jsonData = data.filter(
            (item) => JSON.stringify(item.energyVos) !== "[]"
          );
          if (jsonData.length === 0) {
            this.isNothing2 = true;
          } else {
            this.isNothing2 = false;
            for (let i = 0; i < data.length; i += 1) {
              // 确保下标
              const data1 =
                this.handler().aggregate5MinData(data[i].energyVos) || [];

              inputList.push(data1.map((item) => item.data));
            }
            // 找到最大的数组长度
            const maxLength = Math.max(
              ...inputList.map((inputList) => inputList.length)
            );

            // 使用 reduce 来计算每个下标的和
            const summedArray = Array.from(
              { length: maxLength },
              (_, index) => {
                return inputList.reduce((sum, currentArray) => {
                  return Math.min(
                    Math.floor(
                      sum + (currentArray[index] || 0) / inputList.length
                    ),
                    100
                  );
                }, 0);
              }
            );
            let time = data.filter(
              (item) => JSON.stringify(item.energyVos) !== "[]"
            );
            list = this.handler().formatterDate(
              this.handler().aggregate5MinData(time[0].energyVos)
            );

            const richCss = {
              start: { width: 60, align: "right" },
              end: { width: 60, align: "left" },
            };
            const option = {
              dataZoom: {
                type: "inside",
                minSpan: this.queryData.type === 0 ? 5 : 30,
                preventDefaultMouseMove: false,
              },
              tooltip: {
                extraCssText: "border-radius: 10px",
                backgroundColor:
                  this.$store.state.currentTheme === "dark"
                    ? "#35383F"
                    : "#F3F3F3",
                borderColor:
                  this.$store.state.currentTheme === "dark"
                    ? "#35383F"
                    : "#F3F3F3",
                triggerOn: "none",
                trigger: "axis",
                confine: true,
                position: function (point, params, dom, rect, size) {
                  // 固定在顶部
                  // 获取容器宽度
                  const containerWidth = sbvChart.getWidth();

                  // 根据触发点的横坐标位置决定tooltip应该显示在左侧还是右侧
                  const tooltipWidth = dom.offsetWidth;
                  const posX =
                    point[0] + tooltipWidth > containerWidth
                      ? point[0] - tooltipWidth - 10
                      : point[0] + 10;
                  // 固定在顶部
                  return [posX, "0"];
                },
                axisPointer: {
                  type: "line",
                },
                show: true,
                formatter: function (params) {
                  let htmls = "";
                  params.forEach((v, i) => {
                    htmls += `
                            <div class="chart-tip">
                              <div class="input">
                                  <div class="tips-item">
                                      <span class="circle" style="${
                                        "background:" + v.color
                                      }"></span> ${v.value}%
                                  </div>
                              </div>
                          </div>`;
                  });
                  return (htmls += `<div class="time-charts">
                                  ${params[0].name}
                              </div>`);
                },
              },
              xAxis: {
                show: list.length > 0,
                type: "category",
                boundaryGap: true,
                data: list,
                axisLabel: {
                  showMinLabel: true,
                  showMaxLabel: true,
                  margin: 14,
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#BDBDBD"
                      : "#9E9E9E",
                  formatter: (val, i) => {
                    if (this.queryData.type !== 0) return val;
                    if (i === 0) {
                      return `{start| ${val}}`;
                    }
                    if (i === length) {
                      console.info("进来了");
                      return `{end| ${val}}`;
                    }
                    return val;
                  },
                  rich: richCss,
                },
                axisTick: {
                  show: false,
                },
                axisLine: {
                  show: false,
                },
              },
              yAxis: {
                position: "right",
                type: "value",
                max: 100,
                min: 0,
                interval: 100,
                splitLine: {
                  show: false,
                },
                axisLabel: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#BDBDBD"
                      : "#9E9E9E",
                  formatter: (v) => {
                    return v + "%";
                  },
                },
              },
              series: [
                {
                  name: "SOC",
                  data: summedArray,
                  smooth: true,
                  type: "line",
                  areaStyle: {
                    color:
                      this.$store.state.currentTheme === "dark"
                        ? "rgba(1,242,207,0.14)"
                        : "rgba(0,161,128,0.14)", // 折线颜色
                  },
                  showSymbol: false,
                  lineStyle: {
                    join: "round",
                    cap: "round",
                    color:
                      this.$store.state.currentTheme === "dark"
                        ? "#01F2CF"
                        : "#00A180", //折线颜色
                    width: 1,
                  },
                  itemStyle: {
                    normal: {
                      borderWidth: "1",
                      color: "#01F2CF", //折线颜色
                    },
                  },
                },
              ],
              grid: [
                {
                  top: "10px",
                  left: "20px",
                  right: "2px",
                  bottom: "0",
                  containLabel: true,
                },
              ],
            }; // ECharts 配置项
            sbvChart.setOption(option);
            sbvChart.hideLoading();
          }
          sbvChart.resize();
          this.isLoading = false;
        },
        getSolarFlowPvList: async () => {
          const { data } = await getSolarFlowPvList({
            hemsId: this.queryData.hemsId,
          });
          if (data.length > 0) {
            this.pvList = [
              {
                pvIndex: 0,
                pvName: "ALL",
                type: "",
                deviceId: "",
              },
            ];
            let count = 1;
            for (let i = 0; i < data.length; i += 1) {
              for (let j = 0; j < data[i].pvNum; j += 1) {
                let pvData = {
                  pvName: `PV${count}`,
                  pvIndex: count,
                  type: pvTypeList[j].type,
                  deviceId: data[i].deviceId,
                };
                count++;
                this.pvList.push(pvData);
              }
            }
            let count1 = 1;
            for (let i = 0; i < data.length; i += 1) {
              if (data[i].acCoupling === 1) {
                let pvData = {
                  pvName: `Micro inverter ${count1}`,
                  pvIndex: count,
                  type: 13,
                  deviceId: data[i].deviceId,
                };
                count++;
                count1++;
                this.pvList.push(pvData);
              }
            }
            console.info(this.pvList);
          }
        },
        getCtHemsList: async (type) => {
          acChart.clear();
          this.isNothing = false;
          this.loading = true;
          acChart.showLoading({
            text: "",
            color: "#00A180",
            textColor: "#000",
            maskColor: "transparent",
            zlevel: 1,
            lineWidth: 3,
          });
          let list = [];
          const { data } = await getCtHemsList(this.queryData);
          if (
            JSON.stringify(data) == "{}" ||
            JSON.stringify(data.data) == "{}"
          ) {
            if (type == "home") {
              this.homeFromGrid = 0;
              acChart.hideLoading();
              return;
            }
            acChart.hideLoading();
            this.gridFromGrid = 0;
            this.gridToGrid = 0;
            this.isNothing = true;
          } else {
            if (type == "home") {
              this.homeFromGrid = data.gridInputTotal;
              this.homeTotal += this.homeFromGrid;
              acChart.hideLoading();
              return;
            }
            this.gridToGrid = data.gridReverseTotal;
            this.gridFromGrid = data.gridInputTotal;
            list = this.handler().formatterDate(
              this.handler().aggregate5MinData(data.data[1])
            );

            let grid1Input = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[1])
            );
            let grid2Input = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[3])
            );
            let grid3Input = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[5])
            );
            let resultArrayInput = grid1Input.map((value, index) => {
              return (
                value + (grid2Input[index] || 0) + (grid3Input[index] || 0)
              );
            });
            let grid1Output = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[2])
            );
            let grid2Output = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[4])
            );
            let grid3Output = this.handler().getDates(
              this.handler().aggregate5MinData(data.data[6])
            );

            // 找到第一个长度大于1的数组
            let array =
              [grid1Output, grid2Output, grid3Output].find((arr) =>
                this.currentType == 4 ? arr.length > 0 : arr.length > 1
              ) || [];

            let resultArrayOutput = array.map((value, index) => {
              return (
                value + (grid2Output[index] || 0) + (grid3Output[index] || 0)
              );
            });

            if (data.productType == 25) {
              this.grid1Input = this.handler().getDates(
                this.handler().aggregate5MinData(data.data[10])
              );
              this.grid1Output = this.handler()
                .getDates(this.handler().aggregate5MinData(data.data[11]))
                .map((item) => 0 - item);
            } else {
              this.grid1Input = resultArrayInput;
              this.grid1Output = resultArrayOutput.map((item) => 0 - item);
            }
            this.isNothing = false;
            acChart.hideLoading();
          }
          const richCss = {
            start: { width: 60, align: "right" },
            end: { width: 60, align: "left" },
          };
          const option = {
            dataZoom: {
              type: "inside",
              minSpan: this.queryData.type === 0 ? 5 : 30,
              preventDefaultMouseMove: false,
            },
            tooltip: {
              extraCssText: "border-radius: 10px",
              backgroundColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              borderColor:
                this.$store.state.currentTheme === "dark"
                  ? "#35383F"
                  : "#F3F3F3",
              triggerOn: "none",
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // 获取容器宽度
                const containerWidth = acChart.getWidth();

                // 根据触发点的横坐标位置决定tooltip应该显示在左侧还是右侧
                const tooltipWidth = dom.offsetWidth;
                const posX =
                  point[0] + tooltipWidth > containerWidth
                    ? point[0] - tooltipWidth - 10
                    : point[0] + 10;
                // 固定在顶部
                return [posX, "0"];
              },
              confine: true,
              axisPointer: {
                z: 1,
                type: "line",
                lineStyle: {
                  width: 1,
                  type: "dashed",
                  color: this.handler().getLineColor(),
                },
              },
              show: true,
              formatter: (params) => {
                let htmls = "";
                let text = "";
                params.forEach((v, i) => {
                  let sub = "";
                  text = this.powerDisplay(v.value, this.queryData.type) || 0;
                  if (
                    (v.seriesIndex === 2 || v.seriesIndex === 3) &&
                    v.value !== 0
                  ) {
                    sub = `(${
                      v.value > 0
                        ? this.$t("energy.entLaden")
                        : this.$t("energy.laden")
                    })`;
                  }
                  htmls += `
                            <div class="chart-tip">
                              <div class="input">
                                  <div class="tips-item">
                                      <span class="circle" style="${
                                        "background:" + v.color
                                      }"></span> ${text} ${v.seriesName} ${sub}
                                  </div>
                              </div>
                          </div>`;
                });
                return (htmls += `<div class="time-charts">
                                  ${params[0].name}
                              </div>`);
              },
            },
            legend: {
              show: false,
              icon: "circle",
              type: "plain",
              itemWidth: 12,
              itemHeight: 12,
              bottom: 12,
            },
            xAxis: {
              type: "category",
              boundaryGap: true,
              data: list,
              axisLabel: {
                showMinLabel: true,
                showMaxLabel: true,
                margin: 14,
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (val, i) => {
                  if (this.queryData.type !== 0) return val;
                  if (i === 0) {
                    return `{start| ${val}}`;
                  }
                  if (i === length) {
                    console.info("进来了");
                    return `{end| ${val}}`;
                  }
                  return val;
                },
                rich: richCss,
              },
              axisTick: {
                show: false,
                alignWithLabel: true,
              },
              axisLine: {
                show: true,
                // onZero: false,
                lineStyle: {
                  type: "dashed",
                  color: "#616161",
                  width: "1",
                },
              },
            },
            yAxis: {
              position: "right",
              type: "value",
              show: true,
              splitNumber: 2,
              splitLine: {
                show: true,
                lineStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(255,255,255,0.15)"
                      : "rgba(204,204,204,0.2)",
                  type: "dashed",
                },
              },
              axisLabel: {
                color:
                  this.$store.state.currentTheme === "dark"
                    ? "#BDBDBD"
                    : "#9E9E9E",
                formatter: (v, i) => {
                  let max = acChart.getModel().getComponent("yAxis").axis.scale
                    ._extent[1];
                  let maxLabel = this.powerDisplay(v, this.queryData.type);
                  let maxUnit = this.powerDisplay(
                    max,
                    this.queryData.type
                  ).split(" ")[1];
                  if (v === 0) {
                    return v;
                  }
                  if (v !== max) {
                    if (maxUnit === maxLabel.split(" ")[1]) {
                      return maxLabel.split(" ")[0];
                    }
                    return maxLabel;
                  } else {
                    return maxLabel;
                  }
                },
              },
            },
            series: [
              {
                barWidth: "30%",
                stack: this.queryData.type === 0 ? "" : "bar",
                name: this.$t("system.fromGrid"),
                data: this.grid1Input,
                smooth: true,
                type: this.queryData.type === 0 ? "line" : "bar",
                areaStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(224,224,224,0.14)"
                      : "rgba(117,117,117,0.5)",
                },
                showSymbol: false,
                lineStyle: {
                  join: "round",
                  cap: "round",
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#E0E0E0"
                      : "rgba(117,117,117,0.8)", //折线颜色
                  width: 1,
                },
                itemStyle: {
                  borderWidth: 2,
                  borderRadius: 14,
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "#E0E0E0"
                      : "#757575", //折线颜色
                },
              },
              {
                barWidth: "30%",
                stack: this.queryData.type === 0 ? "" : "bar",
                name: this.$t("system.toGrid"),
                data: this.grid1Output,
                smooth: true,
                type: this.queryData.type === 0 ? "line" : "bar",
                areaStyle: {
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(224,224,224,0.14)"
                      : "rgba(117,117,117,0.5)",
                },
                showSymbol: false,
                lineStyle: {
                  join: "round",
                  cap: "round",
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(224,224,224,0.5)"
                      : "rgba(117,117,117,0.8)", //折线颜色
                  width: 1,
                },
                itemStyle: {
                  borderWidth: 2,
                  borderRadius: 15,
                  color:
                    this.$store.state.currentTheme === "dark"
                      ? "rgba(224,224,224,0.5)"
                      : "#757575", //折线颜色
                },
              },
            ],
            grid: [
              {
                top: "10",
                left: "20px",
                right: "0",
                bottom: "0",
                containLabel: true,
              },
            ],
          }; // ECharts 配置项

          acChart.setOption(option);
          acChart.resize();
          this.isLoading = false;
        },
      };
    },
    handler() {
      return {
        navigateTime: (unit, direction) => {
          if (direction === "previous") {
            return dayjs(this.queryData.beginDate).subtract(1, unit);
          } else if (direction === "next") {
            return dayjs(this.queryData.beginDate).add(1, unit);
          } else {
            throw new Error('Invalid direction. Use "forward" or "backward".');
          }
        },
        updateContentHeight: () => {
          this.clientHeight = this.$refs.content.scrollHeight;
          this.updateAppHeight(this.clientHeight);
        },
        getLineColor: () => {
          const colors = {
            dark: {
              solar: "#FCB76B",
              battery: "#01F2CF",
              home: "#33AFFF",
              default: "#E0E0E0",
            },
            light: {
              solar: "#FF9A00",
              battery: "rgba(0,161,128,0.8)",
              home: "rgba(51,175,255,0.8)",
              default: "rgba(117,117,117,0.8)",
            },
          };
          const currentTheme =
            this.$store.state.currentTheme === "dark" ? "dark" : "light";
          if (this.isShowSolar) {
            return colors[currentTheme].solar;
          } else if (this.isShowBattery) {
            return colors[currentTheme].battery;
          } else if (this.isShowHome) {
            return colors[currentTheme].home;
          } else {
            return colors[currentTheme].default;
          }
        },
        // 函数计算每5分钟的平均值并处理不足5个点的情况
        aggregate5MinData: (data) => {
          if (this.currentType === 0 && data) {
            const result = [];
            const totalMinutes = Math.min(data.length, 24 * 60); // 限制为24小时内的分钟数

            for (let i = 0; i < totalMinutes; i += 5) {
              // 取出当前5个数据点
              let slice = data.slice(i, i + 5);

              // 若不足5个数据点则不要了
              if (slice.length < 5) {
                continue;
              }

              // 计算平均值
              const sum = slice.reduce((acc, cur) => acc + cur.data, 0);
              const avg = sum / 5;

              // 计算当前时间（每5分钟的时间点）
              const minutes = i; // 当前的分钟数
              const hours = Math.floor(minutes / 60);
              const finalMinutes = minutes % 60;

              // 只允许输出到23:59
              // 格式化为YYYY-MM-DD HH:MM
              const timeString = `${String(hours).padStart(2, "0")}:${String(
                finalMinutes
              ).padStart(2, "0")}`;

              // 将结果存储在数组中
              result.push({ dateTime: timeString, data: avg });
            }
            result.splice(-1);
            console.info(result);
            return result;
          }
          return data;
        },
        formatterArrayData: (data, type1, type2) => {
          let arr = [];
          // 如果有两个下标的存在才需要相加
          if (type2) {
            for (let i = 0; i < data.length; i += 1) {
              // 确保下标
              const data1 =
                this.handler().aggregate5MinData(data[i].data[type1]) || [];
              const data5 =
                this.handler().aggregate5MinData(data[i].data[type2]) || [];
              const combinedData =
                data1[0]?.dateTime !== ""
                  ? data1.map(
                      (item, index) => item.data + (data5[index]?.data || 0)
                    )
                  : data5.map((item) => item.data);
              arr.push(combinedData);
            }
          } else {
            for (let i = 0; i < data.length; i += 1) {
              // 确保下标
              const data1 =
                this.handler().aggregate5MinData(data[i].data[type1]) || [];

              arr.push(data1.map((item) => item.data));
            }
          }
          // 找到最大的数组长度
          const maxLength = Math.max(...arr.map((arr) => arr.length));

          // 使用 reduce 来计算每个下标的和
          const summedArray = Array.from({ length: maxLength }, (_, index) => {
            return arr.reduce((sum, currentArray) => {
              return sum + (currentArray[index] || 0);
            }, 0);
          });
          return summedArray;
        },
        setDates: (start, end, type) => {
          this.queryData.type = type;
          this.queryData.beginDate = start.format("YYYY-MM-DD");
          this.queryData.endDate = end.format("YYYY-MM-DD");
          switch (this.currentType) {
            case 0:
              this.currentTime = `${this.queryData.beginDate}`;
              break;
            case 2:
              this.currentTime = `${
                this.queryData.beginDate + " ~ " + this.queryData.endDate
              }`;
              break;
            case 3:
              this.currentTime = `${start.format("YYYY-MM")}`;
              break;
            case 4:
              this.currentTime = `${start.format("YYYY")}`;
              break;
          }
        },
        formatterPro: (currentNum, total = 0) => {
          if (currentNum && total !== 0) {
            const result = ((Math.abs(currentNum) / total) * 100).toFixed(2);
            return Math.min(Number(result), 100);
          }
          return 0;
        },
        formatterNum(num) {
          let forNum = 0;
          if (num) {
            if (Math.abs(num) > 1000) {
              forNum = toFixed(num / 1000, 2) + " kWh";
              return forNum;
            }
            return Number(num).toFixed(2) + " Wh";
          }
          return "-- Wh";
        },
        getNum: (e) => {
          if (String(e).indexOf(".") > -1) {
            return toFixed(Number(e), 2);
          } else {
            return Number(e);
          }
        },
        // 滚动事件
        chartScroll: () => {
          // 滚动的时候隐藏tooltip
          acChart.dispatchAction({
            type: "hideTip",
          });
          acChart.dispatchAction({
            type: "updateAxisPointer",
            currTrigger: "leave",
          });
          sbvChart.dispatchAction({
            type: "hideTip",
          });
          sbvChart.dispatchAction({
            type: "updateAxisPointer",
            currTrigger: "leave",
          });
          clearTimeout(this.loop);
          this.isMove = false;
        },
        touchStart: (e) => {},
        touchStarts: (e) => {},
        touchMove: (e) => {
          // e.preventDefault();
        },
        touchMoves: (e) => {
          console.info("移动了", this.isMove);
          e.preventDefault();
        },
        touchEnd: (e) => {
          this.isShowCover = true;
          acChart.setOption({
            dataZoom: {
              disabled: false,
            },
          });

          acChart.dispatchAction({
            type: "updateAxisPointer",
            currTrigger: "leave",
          });
          acChart.dispatchAction({
            type: "hideTip",
          });
          console.info("离开111", this.loop, this.isShowCover);
          this.isMove = false;
          clearTimeout(this.loop);
          this.loop = 0;
          const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
          acChart._zr.handler.dispatch("mouseup", {
            zrX: touch.x,
            zrY: touch.y,
          });
          acChart._zr.handler.dispatch("click", {
            zrX: touch.x,
            zrY: touch.y,
          });
        },
        touchEnds: (e) => {
          sbvChart.setOption({
            dataZoom: {
              disabled: false,
            },
          });
          this.isShowCover = true;

          sbvChart.dispatchAction({
            type: "hideTip",
          });
          sbvChart.dispatchAction({
            type: "updateAxisPointer",
            currTrigger: "leave",
          });
          this.isMove = false;
          clearTimeout(this.loop);
          this.loop = 0;
          const touch = e.mp.changedTouches ? e.mp.changedTouches[0] : {};
          sbvChart._zr.handler.dispatch("mouseup", {
            zrX: touch.x,
            zrY: touch.y,
          });
          sbvChart._zr.handler.dispatch("click", {
            zrX: touch.x,
            zrY: touch.y,
          });
        },
        getDates: (e, type) => {
          if (e) {
            return e.map((item) => item.data);
          }
          return [];
        },
        // 通用数组求和方法
        sumArrays(...arrays) {
          const maxLength = Math.max(...arrays.map((arr) => arr.length));
          return Array.from({ length: maxLength }).map((_, i) => {
            return arrays.reduce((sum, arr) => sum + (arr[i] || 0), 0);
          });
        },
        formatterDate: (e) => {
          let date = [];
          switch (this.currentType) {
            case 0:
              date = e.map((item) => item.dateTime);
              break;
            case 1:
              break;
            case 2:
              const adjusted = [...this.$t("system.list")]; // 创建一个新数组
              const sunday = adjusted.pop(); // 取出周日
              adjusted.unshift(sunday); // 将周日放到最前面
              date = e.map((item) => {
                return adjusted[dayjs(item.dateTime).day()];
              });
              break;
            case 3:
              date = e.map((item) => item.dateTime.split("-")[2]);
              break;
            case 4:
              // 创建01到12的月份数组
              const allMonths = Array.from({ length: 12 }, (_, i) =>
                String(i + 1).padStart(2, "0")
              );

              date = allMonths;
              break;
            default:
              date = e.map((item) => item.dateTime);
              break;
          }
          return date;
        },
      };
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  background: var(--systemBg);
  height: 100%;
  position: relative;
  ::-webkit-scrollbar {
    width: 0 !important;
  }
  ::-webkit-scrollbar {
    width: 0 !important;
    height: 0;
  }
  -webkit-user-select: none;
  .card {
    background: var(--systemBgColor);
    /*box-shadow: var(--boxShadow2);*/
    margin: 0 32rpx 40rpx;
    border-radius: 36rpx;
    overflow: hidden;
  }
  .time-action {
    /*background: var(--color2);*/
    width: 100%;
    overflow: hidden;
    .item-container {
      overflow: hidden;
      display: flex;
      justify-content: center;
      align-items: center;
      .item {
        position: relative;
        z-index: 888;
        width: 100%;
        height: 108rpx;
        line-height: 108rpx;
        text-align: center;
        font-size: 30rpx;
        font-family: Ageo-Medium;
        color: var(--basebg5);
      }
      .active {
        z-index: 1;
        border-radius: 28rpx 28rpx 0 0;
        background: var(--systemContenColor);
        color: var(--success);
        box-shadow: 20px 20px 0 0 var(--systemContenColor),
          -20px 20px 0 0 var(--systemContenColor);
      }
      .active::before {
        z-index: 2;
        content: "";
        position: absolute;
        left: -21px;
        bottom: 0;
        width: 21px;
        height: 108rpx;
        background: var(--systemBgColor);
        border-radius: 0 0 26rpx 0;
      }
      .active::after {
        z-index: 2;
        content: "";
        position: absolute;
        right: -21px;
        bottom: 0;
        width: 21px;
        height: 108rpx;
        background: var(--systemBgColor);
        border-radius: 0 0 0 26rpx;
      }
    }
  }
  .current-time {
    margin-top: 32rpx;
    display: flex;
    justify-content: center;
    justify-content: space-between;
    align-items: center;
    .icon {
      width: 54rpx;
      height: 54rpx;
      img {
        user-select: none;
        width: 54rpx;
        height: 54rpx;
      }
    }
    .text {
      margin: 0 24rpx;
      font-family: Ageo-Medium;
      font-size: 26rpx;
      color: var(--color4);
      text-align: center;
    }
  }
  .content-right {
    border-radius: 0rpx 36rpx 0rpx 0rpx !important;
  }
  .content-left {
    border-radius: 36rpx 0rpx 0rpx 0rpx !important;
  }
  .content {
    background: var(--systemContenColor);
    /*border-radius: 0 36rpx 0 0;*/
    /*width: 670rpx;*/
    padding: 32rpx;
    border-radius: 36rpx;
    .actions {
      background: var(--systemTimeActionColor);
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      border-radius: 28rpx;
      .action-item {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        width: 140rpx;
        img {
          user-select: none;
          width: 48rpx;
          height: 48rpx;
        }
      }
      .active {
        /*box-shadow: var(--boxShadow2);*/
        background: var(--systemActionsActive);
        border-radius: 28rpx;
      }
      .batteryItem {
        margin-left: 10rpx !important;
      }
    }
    .headers {
      border-radius: 20rpx;
      margin-top: 30rpx;
      background: var(--systemTimeActionColor);
      .solar-container {
        position: relative;
        padding: 16rpx 40rpx;
        display: flex;
        align-items: center;
        .power {
          font-family: Ageo-Bold;
          font-size: 36rpx;
          color: var(--color4);
        }
        .text {
          margin-left: 20rpx;
          font-family: Ageo-Medium;
          font-size: 26rpx;
          color: #9e9e9e;
        }
        .icon {
          position: relative;
          margin-left: 10rpx;
          width: 24rpx;
          height: 24rpx;
          img {
            width: 24rpx;
            height: 24rpx;
          }
          .bubble-tail {
            position: absolute;
            bottom: -25rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 10rpx solid transparent; /* 调整底边的半宽 */
            border-right: 10rpx solid transparent; /* 调整底边的半宽 */
            border-bottom: 15rpx solid var(--color3); /* 三角形颜色和高度 */
            content: "";
            z-index: 0;
          }
        }
        .bubble {
          z-index: 788;
          position: absolute;
          top: 80rpx;
          left: 50%;
          transform: translateX(-50%);
          width: 550rpx;
          padding: 25rpx;
          border-radius: 32rpx;
          background: var(--color3);
          .bubble-content {
            word-break: break-word;
            font-family: Ageo-Regular;
            font-size: 28rpx;
            color: var(--basebg6);
          }
        }
      }
      .batteryPower {
        .item {
          position: relative;
          display: flex;
          align-items: center;
          padding: 16rpx 40rpx;
          .power {
            white-space: nowrap;
            font-family: Ageo-Bold;
            font-size: 36rpx;
            color: var(--color4);
          }
          .text {
            text-align: center;
            width: fit-content;
            word-break: break-word;
            margin-left: 20rpx;
            font-family: Ageo-Medium;
            font-size: 26rpx;
            color: var(--basebg5);
          }
          .icon {
            position: relative;
            margin-left: 10rpx;
            width: 24rpx;
            height: 24rpx;
            img {
              width: 24rpx;
              height: 24rpx;
            }
            .bubble-tail {
              position: absolute;
              bottom: -25rpx;
              left: 50%;
              transform: translateX(-50%);
              width: 0;
              height: 0;
              border-left: 10rpx solid transparent; /* 调整底边的半宽 */
              border-right: 10rpx solid transparent; /* 调整底边的半宽 */
              border-bottom: 15rpx solid var(--color3); /* 三角形颜色和高度 */
              content: "";
              z-index: 0;
            }
          }
          .bubble {
            z-index: 788;
            position: absolute;
            top: 80rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 550rpx;
            padding: 25rpx;
            border-radius: 32rpx;
            background: var(--color3);
            .bubble-content {
              word-break: break-word;
              font-family: Ageo-Regular;
              font-size: 28rpx;
              color: var(--basebg6);
            }
          }
        }
        .item:nth-child(2n) {
          padding-top: unset !important;
        }
      }
    }
    .home-bar {
      margin: 32rpx 0;
      display: flex;
      align-items: center;
      .active {
        color: rgba(255, 255, 255, 0.9);
        background: rgba(255, 255, 255, 0.02);
      }
      .activeLight {
        color: rgba(0, 0, 0, 0.9);
        background: #fafafa;
      }
      .home-item {
        padding: 0 30rpx;
        height: 60rpx;
        line-height: 60rpx;
        margin-right: 28rpx;
        font-family: Ageo-Medium;
        font-size: 26rpx;
        color: var(--pvColor);
        border-radius: 16rpx;
      }
    }
    .line-container {
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left {
        display: flex;
        overflow-x: auto;
        .line-list {
          display: flex;
          align-items: center;
          &::-webkit-scrollbar {
            display: none;
            width: 0;
            height: 0;
            color: transparent;
            background: transparent;
          }
        }
      }
      .right {
        .item {
          margin-right: unset !important;
          img {
            width: 42rpx;
            height: 42rpx;
          }
        }
      }
      .active {
        color: rgba(255, 255, 255, 0.9);
        background: rgba(255, 255, 255, 0.02);
      }
      .activeLight {
        color: rgba(0, 0, 0, 0.9);
        background: #fafafa;
      }
      .item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: auto;
        flex-shrink: 0;
        height: 60rpx;
        line-height: 60rpx;
        border-radius: 16rpx;
        margin-right: 28rpx;
        font-family: Ageo-Medium;
        font-size: 26rpx;
        color: var(--pvColor);
        padding: 0 26rpx;
        img {
        }
      }
    }
    .echart-title {
      margin-top: 40rpx;
      font-family: Ageo-Regular;
      font-size: 24rpx;
      color: var(--color4);
    }
    .ac-container {
      position: relative;
      margin-top: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      height: 520rpx;
      .echart-title-top {
        position: absolute;
        top: -30rpx;
        right: 0;
        font-family: Ageo-Regular;
        font-size: 24rpx;
        color: var(--basebg10);
      }
      .echart-title-bottom {
        position: absolute;
        right: 0;
        bottom: 80rpx;
        font-family: Ageo-Regular;
        font-size: 24rpx;
        color: var(--basebg10);
      }
      .ac-chart {
        flex: 1;
        height: 430rpx;
      }
      /deep/ canvas {
        width: 100%;
      }
      .no-data {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: 0;
        width: 100%;
      }
    }
    .sbv-container {
      margin-top: 40rpx;
      border-radius: 16rpx;
      padding: 40rpx;
      border: 1px solid var(--color3);
      .sbv-header {
        .echarts-title {
          font-size: 28rpx;
          font-family: Ageo-Medium;
          color: var(--color4);
        }
        .sbv-ac {
          margin-top: 32rpx;
          width: 100%;
          height: 370rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          .ac-chart {
            width: 100%;
            height: 370rpx;
          }
        }
      }
    }
    .info-container {
      margin: 40rpx auto 0;
      padding: 32rpx;
      border-radius: 16rpx;
      border: 1rpx solid var(--color3);
      .header {
        .left {
          word-break: break-word;
          text-align: left;
          font-family: Ageo-Medium;
          font-size: 32rpx;
          color: #999999;
        }
        .right {
          word-break: break-word;
          text-align: right;
          font-family: Ageo-Medium;
          font-size: 28rpx;
          color: #999999;
        }
      }
      .total {
        margin-top: 25rpx;
        font-family: Ageo-SemiBold;
        font-size: 32rpx;
        color: var(--color5);
      }
      .line {
        margin-top: 24rpx;
        width: 100%;
        height: 32rpx;
        background: var(--basebg3);
        border-radius: 4rpx;
        overflow: hidden;
        display: flex;
        align-items: center;
        .line-active {
          height: 32rpx;
        }
        .home {
          background: var(--info);
        }
        .storage {
          background: var(--success);
        }
        .grid {
          background: var(--basebg7);
        }
      }
      .radio {
        margin-bottom: 4rpx;
        margin-right: 8rpx;
        width: 40rpx;
        height: 40rpx;
      }
      .home {
        background: var(--info);
      }
      .storage {
        background: var(--success);
      }
      .grid {
        background: var(--basebg7);
      }
      .solar {
        background: var(--waring);
      }
      .total-info {
        margin-top: 32rpx;
        .item {
          margin-bottom: 38rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .left {
            flex: 1;
            display: flex;
            align-items: center;
            word-break: break-word;
            font-family: Ageo-Medium;
            font-size: 28rpx;
            color: var(--color4);
            .text {
              position: relative;
              word-break: break-word;
              display: inline-block;
              width: 280rpx;
              img {
                margin-left: 12rpx;
                vertical-align: middle;
                display: inline-block;
                width: 28rpx;
                height: 28rpx;
              }
              .bubble {
                position: absolute;
                bottom: 47rpx;
                left: -50rpx;
                width: 550rpx;
                padding: 25rpx;
                border-radius: 32rpx;
                background: var(--color3);
                .bubble-content {
                  word-break: break-word;
                  font-family: Ageo-Regular;
                  font-size: 28rpx;
                  color: var(--basebg6);
                }
                .bubble-tail {
                  position: absolute;
                  bottom: -10rpx;
                  left: 163rpx;
                  width: 0;
                  height: 0;
                  border-style: solid;
                  border-width: 10rpx 10rpx 0;
                  border-color: var(--color3) transparent transparent;
                  content: "";
                  z-index: 0;
                }
              }
            }
          }
          .right {
            display: flex;
            align-items: center;
            color: var(--color4);
            font-family: Ageo-Medium;
            font-size: 28rpx;
            .num {
            }
            .schedule {
              margin-left: 24rpx;
            }
          }
        }
        .item:last-child {
          margin-bottom: unset !important;
        }
      }
      .batter-item {
        .batter-header {
          font-family: Ageo-Medium;
          font-size: 28rpx;
          color: var(--color4);
        }
        .total-info {
          .item {
            margin-top: 32rpx;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 40rpx;
            .left {
              display: flex;
              align-items: center;
              font-family: Ageo-Medium;
              font-size: 28rpx;
              color: var(--color4);
            }
            .right {
              display: flex;
              align-items: center;
              color: var(--color4);
              font-family: Ageo-Medium;
              font-size: 28rpx;
              .num {
                display: inline-block;
              }
              .schedule {
                width: 62rpx;
                margin-left: 24rpx;
              }
            }
          }
          .border {
            margin-bottom: 40rpx !important;
            margin-bottom: 40rpx;
            border-bottom: 1rpx solid var(--color3);
          }
        }
      }
    }
  }
  /deep/ .modal-content {
    left: 0;
    right: 0;
    border: 2rpx solid var(--color3);
  }
  /deep/ .modal-title {
    padding: 40rpx 0 !important;
    font-family: Ageo-SemiBold !important;
    font-weight: unset !important;
    font-size: 36rpx !important;
    color: var(--color4) !important;
  }
  /deep/ .modal-close {
    top: 50rpx !important;
    right: 50rpx !important;
  }
  .select-container {
    height: 800rpx;
    overflow: auto;
    margin: 0 40rpx;
    padding: 50rpx 0;
    border-top: 1px solid var(--color3);
    .select-item {
      padding: 32rpx;
      width: 100%;
      background: var(--color3);
      border-radius: 20rpx;
      font-family: Ageo-Bold;
      font-size: 32rpx;
      color: var(--color4);
      & + .select-item {
        margin-top: 22rpx;
      }
    }
    .active {
      border: 2rpx solid var(--color4);
    }
  }
}
</style>
